package com.nari.ncps.screen.service.impl.coal;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.nari.ncps.screen.entity.coal.CoalProdoperSales;
import com.nari.ncps.screen.entity.coal.CoalProdoperSalesCalorific;
import com.nari.ncps.screen.entity.coal.CoalProdoperSalesStructure;
import com.nari.ncps.screen.entity.coal.CoalProdoperTransport;
import com.nari.ncps.screen.mapper.coal.CoalProdoperSalesCalorificMapper;
import com.nari.ncps.screen.mapper.coal.CoalProdoperSalesMapper;
import com.nari.ncps.screen.service.coal.CoalProdoperSalesCalorificService;
import com.nari.ncps.screen.vo.coal.CoalSalesStructureVO;
import com.nari.ncps.screen.vo.coal.CoalSalesVO;
import com.nari.ncps.screen.vo.coal.CoalTransportVO;
import io.swagger.v3.oas.annotations.media.Schema;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.math.RoundingMode;
import java.time.LocalDate;
import java.util.*;

/**
 * <p>
 * 安全环保危险废弃物处置表 服务实现类
 * </p>
 *
 * @author wanghuiqiang
 * @since 2025-11-06
 */
@Service
public class CoalProdoperSalesCalorificServiceImpl extends ServiceImpl<CoalProdoperSalesCalorificMapper, CoalProdoperSalesCalorific> implements CoalProdoperSalesCalorificService {


    @Autowired
    private CoalProdoperSalesMapper  coalProdoperSalesMapper;

    @Override
    public List<CoalTransportVO> getSalesTransport(Integer year) {

        // 如果year为null，使用当前年份
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();

        // 构建最近6个月的年月列表
        List<CoalTransportVO> resultList = new ArrayList<>();

        // 查询当前年及去年的数据（可能跨年）
        List<Integer> years = new ArrayList<>();
        years.add(currentYear - 1);
        years.add(currentYear);

        LambdaQueryWrapper<CoalProdoperSalesCalorific> query = new LambdaQueryWrapper<>();
        query.in(CoalProdoperSalesCalorific::getYear, years).eq(CoalProdoperSalesCalorific::getOrgCode, "100360");

        List<CoalProdoperSalesCalorific> dataList = this.list(query);

        // 处理数据为空的情况
        if (dataList == null || dataList.isEmpty()) {
            // 返回空数据但包含年月信息
            for (int i = 5; i >= 0; i--) {
                LocalDate monthDate = LocalDate.of(currentYear, currentMonth, 1).minusMonths(i);
                CoalTransportVO vo = new CoalTransportVO();
                vo.setYear(monthDate.getYear());
                vo.setMonth(monthDate.getMonthValue());
                vo.setRoadTransport(BigDecimal.ZERO);
                vo.setBeltTransport(BigDecimal.ZERO);
                vo.setRailTransport(BigDecimal.ZERO);
                resultList.add(vo);
            }
            return resultList;
        }

        // 按年月和运输类型分组汇总数据
        // Map结构: "year-month" -> transportType -> sum(transportVolume)
        Map<String, Map<Integer, BigDecimal>> monthlyData = new HashMap<>();

        for (CoalProdoperSalesCalorific transport : dataList) {
            if (transport.getYear() != null && transport.getMonth() != null && transport.getTransMode() != null) {
                String yearMonth = transport.getYear() + "-" + transport.getMonth();
                monthlyData.putIfAbsent(yearMonth, new HashMap<>());

                Map<Integer, BigDecimal> typeMap = monthlyData.get(yearMonth);
                String transportType = transport.getTransMode();

                // 汇总该年月该类型的运输量
                BigDecimal currentSum = typeMap.getOrDefault(transportType, BigDecimal.ZERO);
                if (transport.getActualSales() != null) {
                    typeMap.put(Integer.valueOf(transportType), currentSum.add(transport.getActualSales()));
                }
            }
        }

        // 构建最近6个月的结果
        for (int i = 5; i >= 0; i--) {
            LocalDate monthDate = LocalDate.of(currentYear, currentMonth, 1).minusMonths(i);
            int queryYear = monthDate.getYear();
            int queryMonth = monthDate.getMonthValue();

            CoalTransportVO vo = new CoalTransportVO();
            vo.setYear(queryYear);
            vo.setMonth(queryMonth);

            // 获取该年月的数据
            String yearMonth = queryYear + "-" + queryMonth;
            Map<Integer, BigDecimal> typeMap = monthlyData.get(yearMonth);

            if (typeMap != null) {
                // 0：汽运
                vo.setRoadTransport(typeMap.getOrDefault(0, BigDecimal.ZERO));
                // 1：皮带
                vo.setBeltTransport(typeMap.getOrDefault(1, BigDecimal.ZERO));
                // 2：铁运
                vo.setRailTransport(typeMap.getOrDefault(2, BigDecimal.ZERO));
            } else {
                vo.setRoadTransport(BigDecimal.ZERO);
                vo.setBeltTransport(BigDecimal.ZERO);
                vo.setRailTransport(BigDecimal.ZERO);
            }

            resultList.add(vo);
        }

        return resultList;


    }

    @Override
    public CoalSalesStructureVO getSalesStructure(Integer year) {
        // 如果未指定年份，使用当前年份
        if (year == null) {
            year = LocalDate.now().getYear();
        }

        // 查询指定年份的数据
        LambdaQueryWrapper<CoalProdoperSalesCalorific> wrapper = Wrappers.lambdaQuery();
        wrapper.eq(CoalProdoperSalesCalorific::getYear, year).eq(CoalProdoperSalesCalorific::getDateType,0);

        List<CoalProdoperSalesCalorific> structureList = this.list(wrapper);

        // 初始化VO
        CoalSalesStructureVO vo = new CoalSalesStructureVO();
        BigDecimal longTermSales = BigDecimal.ZERO;  // 长协煤销售量
        BigDecimal marketSales = BigDecimal.ZERO;    // 市场煤销售量
        BigDecimal internalSales = BigDecimal.ZERO;  // 系统内销售量
        BigDecimal externalSales = BigDecimal.ZERO;  // 系统外销售量

        // 遍历数据进行聚合统计
        for (CoalProdoperSalesCalorific structure : structureList) {
            // 将吨转换为万吨（除以10000）
            BigDecimal volumeInWanTon = structure.getActualSales()
                    .divide(new BigDecimal("10000"), 2, RoundingMode.HALF_UP);

            // 按合同类型统计
            if (structure.getContractMode() != null && structure.getContractMode() == 1) {
                // 长协煤
                longTermSales = longTermSales.add(volumeInWanTon);
            } else if (structure.getContractMode() != null && structure.getContractMode() == 2) {
                // 市场煤
                marketSales = marketSales.add(volumeInWanTon);
            }

            // 按销售渠道统计
            if (StringUtils.isNotEmpty(structure.getSystemType()) && structure.getSystemType().equals("01")) {
                // 系统内
                internalSales = internalSales.add(volumeInWanTon);
            } else if (StringUtils.isNotEmpty(structure.getSystemType()) && structure.getSystemType().equals("02")) {
                // 系统外
                externalSales = externalSales.add(volumeInWanTon);
            }
        }

        vo.setLongTermSales(longTermSales);
        vo.setMarketSales(marketSales);
        vo.setInternalSales(internalSales);
        vo.setExternalSales(externalSales);

        return vo;
    }

    @Override
    public CoalSalesVO getCoalSales(Integer year) {
        int currentYear = year != null ? year : LocalDate.now().getYear();
        int currentMonth = LocalDate.now().getMonthValue();

        CoalSalesVO vo = new CoalSalesVO();

        LambdaQueryWrapper<CoalProdoperSalesCalorific> yearQuery = new LambdaQueryWrapper<>();
        yearQuery.eq(CoalProdoperSalesCalorific::getYear, currentYear).eq(CoalProdoperSalesCalorific::getDateType, 0).eq(CoalProdoperSalesCalorific::getOrgCode, "100360");
        List<CoalProdoperSalesCalorific> structureList = this.list(yearQuery);

        BigDecimal annualPlan = BigDecimal.ZERO;            // 年计划完成情况(万吨)
        BigDecimal annualCompletionRate = BigDecimal.ZERO;  // 年当前完成率(%)
        BigDecimal annualActual = BigDecimal.ZERO;          // 年当前完成情况(万吨)
        BigDecimal annualHighHeat = BigDecimal.ZERO;        // 年高热当前完成(万吨) 04
        BigDecimal annualTypicalHeat = BigDecimal.ZERO;     // 年标热当前完成(万吨) 03
        BigDecimal annualGradeHeat = BigDecimal.ZERO;       // 年普热当前完成(万吨) 02
        BigDecimal annualLowHeat = BigDecimal.ZERO;         // 年低热当前完成(万吨) 01

        // 遍历数据进行聚合统计
        for (CoalProdoperSalesCalorific structure : structureList) {
            // 将吨转换为万吨（除以10000）
            BigDecimal volumeInWanTon = structure.getActualSales();
            annualActual =  annualActual.add(volumeInWanTon);
            if(StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("01")) {
                annualLowHeat = annualLowHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("02")) {
                annualGradeHeat = annualGradeHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("03")) {
                annualTypicalHeat  = annualTypicalHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("04")) {
                annualHighHeat = annualHighHeat.add(volumeInWanTon);
            }
        }

        vo.setAnnualPlan(annualPlan);
        vo.setAnnualCompletionRate(annualCompletionRate);
        vo.setAnnualActual(annualActual);
        vo.setAnnualHighHeat(annualHighHeat);
        vo.setAnnualLowHeat(annualLowHeat);
        vo.setAnnualGradeHeat(annualGradeHeat);
        vo.setAnnualTypicalHeat(annualTypicalHeat);



        BigDecimal monthlyPlan = BigDecimal.ZERO;               // 月计划完成情况(万吨)
        BigDecimal monthlyCompletionRate = BigDecimal.ZERO;     // 月当前完成率(%)
        BigDecimal monthlyActual = BigDecimal.ZERO;             // 月当前完成情况(万吨)
        BigDecimal monthlyLowHeat = BigDecimal.ZERO;            // 月低热当前完成(万吨)  01
        BigDecimal monthlyHighHeat = BigDecimal.ZERO;           // 月优热当前完成(万吨)  04
        BigDecimal monthlyGradeHeat = BigDecimal.ZERO;          // 月普热当前完成(万吨)  02
        BigDecimal monthlyTypicalHeat = BigDecimal.ZERO;        // 月标热当前完成(万吨)  03

        LambdaQueryWrapper<CoalProdoperSalesCalorific> monthQuery = new LambdaQueryWrapper<>();
        monthQuery.eq(CoalProdoperSalesCalorific::getYear, currentYear).eq(CoalProdoperSalesCalorific::getMonth, currentMonth).eq(CoalProdoperSalesCalorific::getDateType, 1).eq(CoalProdoperSalesCalorific::getOrgCode, "100360");
        List<CoalProdoperSalesCalorific> dataList = this.list(monthQuery);
        // 遍历数据进行聚合统计
        for (CoalProdoperSalesCalorific structure : dataList) {
            // 将吨转换为万吨（除以10000）
            BigDecimal volumeInWanTon = structure.getActualSales();
            monthlyActual =  monthlyActual.add(volumeInWanTon);
            if(StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("01")) {
                monthlyLowHeat = monthlyLowHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("02")) {
                monthlyGradeHeat = monthlyGradeHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("03")) {
                monthlyTypicalHeat  = monthlyTypicalHeat.add(volumeInWanTon);
            }
            if (StringUtils.isNotEmpty(structure.getCalorificRange()) && structure.getCalorificRange().equals("04")) {
                monthlyHighHeat = monthlyHighHeat.add(volumeInWanTon);
            }
        }

        vo.setMonthlyPlan(monthlyPlan);
        vo.setMonthlyCompletionRate(monthlyCompletionRate);
        vo.setMonthlyActual(monthlyActual);
        vo.setMonthlyLowHeat(monthlyLowHeat);
        vo.setMonthlyHighHeat(monthlyHighHeat);
        vo.setMonthlyGradeHeat(monthlyGradeHeat);
        vo.setMonthlyTypicalHeat(monthlyTypicalHeat);

        LambdaQueryWrapper<CoalProdoperSales> yearWrapper = new LambdaQueryWrapper<>();
        yearWrapper.eq(CoalProdoperSales::getYear, currentYear).eq(CoalProdoperSales::getDateType, 0).eq(CoalProdoperSales::getOrgCode, "100360");
        CoalProdoperSales result = coalProdoperSalesMapper.selectOne(yearWrapper);
        vo.setAnnualPlan(result.getAnnualPlan());
        vo.setAnnualCompletionRate(annualActual.divide(result.getAnnualPlan(),2, RoundingMode.HALF_UP));


        LambdaQueryWrapper<CoalProdoperSales> monthWrapper = new LambdaQueryWrapper<>();
        monthWrapper.eq(CoalProdoperSales::getMonth, currentMonth).eq(CoalProdoperSales::getDateType, 1).eq(CoalProdoperSales::getOrgCode, "100360");
        CoalProdoperSales monthResult = coalProdoperSalesMapper.selectOne(monthWrapper);
        if (monthResult != null) {
            vo.setMonthlyPlan(monthResult.getMonthlyPlan());
        }
        if (result.getAnnualPlan()!=null) {
            vo.setMonthlyCompletionRate(monthlyActual.divide(result.getAnnualPlan(),2, RoundingMode.HALF_UP));
        }




        return vo;
    }
}
